package cn.liyicun.school.car2.base;

import com.jfinal.captcha.CaptchaRender;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;

import cn.liyicun.school.car2.error.ErrorRunTimeException;
import cn.liyicun.school.car2.error.LoginRunTimeException;
import cn.liyicun.school.car2.model.UserInfo;

public abstract class BaseController<T> extends Controller {
	protected static String SALT_PUBLIC = "cn.liyicun.school.car2.controller.user";

	public void myRenderJson(int code, String msg, Object data) {
		myRenderJsonBean(new ResultBean(code, msg, data));
	}

	public void myRenderJsonBean(ResultBean bean) {
		renderJson(bean);
	}

	public void myRenderJson(Object data) {
		myRenderJsonBean(new ResultBean(200, "ok", data));
	}

	public void myRenderJsonSuccess(String msg) {
		myRenderJsonBean(new ResultBean(200, StrKit.isBlank(msg) ? "ok" : msg));
	}

	
	public void myRenderJsonLink(String msg,String link) {
		myRenderJsonBean(new ResultBean(201, msg, link));
	}
	
	
	public void myRenderJsonError(String msg) {
		myRenderJsonBean(new ResultBean(404, msg, null));
	}

	public String buildPasword(String password, String salt){
		return HashKit.md5(password + SALT_PUBLIC + salt);
	}
	

	public boolean paswordEquals(String password, UserInfo data){
	return buildPasword(password, data.getSalt()).equals(data.getPassword());
	}
	
	
	public void verification(boolean flag, String msg) {
		if (flag) {
			throw new ErrorRunTimeException(msg);
		}
	}

	public void verificationCaptcha(String verify_code) {
		if (!CaptchaRender.validate(this, verify_code)) {
			throw new ErrorRunTimeException(405, "验证码不正确!");
		}
	}

	public abstract String getLoginName();

	public T getLoginAccount() {
		return getLoginAccount(true);
	}

	public T getLoginAccount(boolean flag) {
		T data = getSessionAttr(getLoginName());
		if (data == null && flag)
			throw new LoginRunTimeException();
		return data;
	}

	public void setLoginAccount(T data) {
		setSessionAttr(getLoginName(), data);
	}

	public void logOutAccount() {
		removeSessionAttr(getLoginName());

	}
}
